<template>
  <div>
    <el-main>
      <div class="form_title">角色信息</div>
      <div class="form_content">
        <el-form
          ref="form"
          label-width="80px"
          :model="model"
          :rules="rules"
        >
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="名称" prop="status">
                <el-input
                  placeholder="请输入名称"
                  v-model="model.name"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="排序" prop="sortIndex">
                <el-input-number v-model="model.sortIndex" :min="1" :max="1000" placeholder="请输入排序"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" :rows="5" v-model="model.remark" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="form_title">菜单信息</div>
      <div class="form_content">
        <el-table
          ref="menuTable"
          :data="menuTable"
          :border="true"
          style="width: 100%"
          size="small"
          row-key="id"
          :tree-props="{children: 'treeList', hasChildren: 'hasChildren'}"
          @selection-change="handleMenuSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            prop="name"
            label="名称"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="code"
            label="编码"
            show-overflow-tooltip
          ></el-table-column>
        </el-table>
      </div>
      <div class="form_title">权限信息</div>
      <div class="form_content">
        <el-table
          ref="functionTable"
          :data="functionTable"
          :border="true"
          style="width: 100%"
          size="small"
          @selection-change="handleFunctionSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            prop="name"
            label="名称"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="code"
            label="编码"
            show-overflow-tooltip
          ></el-table-column>
        </el-table>
      </div>
    </el-main>
    <el-footer>
      <el-button
        icon="el-icon-close"
        size="small"
        @click="$router.go(-1)"
      >取消</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-check"
        size="small"
        @click="handleSave"
      >保存</el-button
      >
    </el-footer>
  </div>
</template>

<script>
  import {searchMenu} from "@/api/system/menu";
  import {searchFunction} from "@/api/system/function";
  import {insertRole,updateRole,viewRole} from "@/api/system/role";
  import {ApiError} from "@/utils/errors";

  export default {
    data() {
      return {
        isEdit: false,
        model: {
          sortIndex: 1,
          remark: null
        },
        rules: {
          name: [{ required: true, message: "名称必须填写", trigger: "blur" }],
          sortIndex: [{ required: true, message: "排序必须填写", trigger: "blur" }]
        },
        menuTable: [],
        menuKey: null,
        menuMultipleSelection: [],
        functionTable: [],
        functionKey: null,
        functionMultipleSelection: []
      }
    },
    created() {
      const id = this.$route.query.id;
      if(id){
        this.isEdit = true;
        this.get(id);
      }else{
        this.getMenu();
        this.getFunction();
      }
    },
    methods: {
      get(id){
        const that = this;
        const params = {id:id};
        viewRole(params).then(res => {
          if (res.status == 200) {
            if (!res.data.success) {
              return this.$message.error(ApiError.msg(res.data.message));
            }
            that.model.id = res.data.data.id;
            that.model.name = res.data.data.name;
            that.model.sortIndex = res.data.data.sortIndex;
            that.model.remark = res.data.data.remark;
            that.getMenu(res.data.data.menus);
            that.getFunction(res.data.data.functions);
          }
        });
      },
      getMenu(menus) {
        const that = this;
        searchMenu().then(res => {
          if (res.status == 200) {
            if (!res.data.success) {
              return this.$message.error(ApiError.msg(res.data.message));
            }
            const data = res.data.data;
            that.menuTable = data;
            if(menus){
              that.menuKey = {};
              for(let i=0;i<data.length;i++){
                that.menuKey[data[i].id] = data[i];
                that.setMenu(data[i]);
              }
              that.$nextTick(()=>{
                for(let i=0;i<menus.length;i++){
                  this.$refs.menuTable.toggleRowSelection(that.menuKey[menus[i].id]);
                }
              });
            }
          }
        });
      },
      setMenu(menu){
        if(menu.treeList){
          for(let i=0;i<menu.treeList.length;i++){
            this.menuKey[menu.treeList[i].id] = menu.treeList[i];
            this.setMenu(menu.treeList[i]);
          }
        }
      },
      handleMenuSelectionChange(val){
        this.menuMultipleSelection = val;
      },
      getFunction(functions){
        const that = this;
        searchFunction().then(res => {
          if (res.status == 200) {
            if (!res.data.success) {
              return this.$message.error(ApiError.msg(res.data.message));
            }
            const data = res.data.data;
            that.functionTable = data;
            if(functions){
              that.functionKey = {};
              for(let i=0;i<data.length;i++){
                that.functionKey[data[i].id] = data[i];
              }
              that.$nextTick(()=>{
                for(let i=0;i<functions.length;i++){
                  this.$refs.functionTable.toggleRowSelection(that.functionKey[functions[i].id]);
                }
              });
            }
          }
        });
      },
      handleFunctionSelectionChange(val){
        this.functionMultipleSelection = val;
      },
      handleSave() {
        const that = this;
        this.$refs.form.validate(valid => {
          if (!valid) {
            return;
          }
          that.model.menuIds = [];
          for(let i=0;i<that.menuMultipleSelection.length;i++){
            that.model.menuIds.push(that.menuMultipleSelection[i].id);
          }
          that.model.functionIds = [];
          for(let i=0;i<that.functionMultipleSelection.length;i++){
            that.model.functionIds.push(that.functionMultipleSelection[i].id);
          }
          let saveModelFunction = insertRole;
          if (that.isEdit) {
            saveModelFunction = updateRole;
          }
          saveModelFunction(that.model).then(res => {
            if (res.status == 200) {
              if (!res.data.success) {
                return this.$message.error(ApiError.msg(res.data.message));
              }
              this.$message.success(this.isEdit ? "修改角色成功" : "新增角色成功");
              that.$router.go(-1);
            }
          });
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .form_title {
    padding-bottom: 20px;
    font-size: 16px;
    font-weight: 700;
    color: rgba(0, 0, 0, 0.85);
  }
  .form_content {
    padding-right: 16px;
  }
  .input_suffix {
    display: inline-block;
    padding: 0 6px;
  }
  .el-divider {
    margin: 6px 0 16px;
  }
  .add_new_batch {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 16px;
    height: 45px;
    border: 1px dashed #d9d9d9;
    cursor: pointer;
    color: #8c939d;
  }
  .batch_block {
    margin-top: 16px;
  }
  .batch_block:first-child {
    margin-top: 0;
  }
  @import "@/styles/full-form";
  @import "@/styles/common-table";
</style>
